
define(function (require) {
    var SIPClient = {
        simple: null,
        ua: {},
        state: 'disabled',
        startTime: null,
        durationCounterInterval: null,
        incomingLayerIndex: null,
        lastSetTimeout: null,
        set_phone_state: function(v) {
            this.state = v;
            this.startTime = null;
            if (this.durationCounterInterval != null) {
                clearInterval(this.durationCounterInterval);        
                this.durationCounterInterval = null;
            }
            if (this.incomingLayerIndex != null) {
                Layer.close(this.incomingLayerIndex);
                this.incomingLayerIndex = null;
            }
            $('#phone_status').html('');
            document.getElementById('audio_ringin').pause();
            document.getElementById('audio_ringback').pause();
            document.getElementById('audio_ringback').currentTime = 0;
            switch (v) {
                case 'idle':
                    $('#phone_num').removeAttr('disabled').val('AIScript-225');
                    $('#phone_call_btn').removeAttr('disabled').removeClass('btn-default btn-success btn-danger').addClass('btn-success').find('i').removeClass('fa-phone fa-remove').addClass('fa-phone');
                    break;
                case 'ringing':
                    document.getElementById('audio_ringin').currentTime = 0;
                    document.getElementById('audio_ringin').play();
                case 'calling':
                    $('#phone_num').attr('disabled', 'disabled');
                    $('#phone_call_btn').removeAttr('disabled').removeClass('btn-default btn-success btn-danger').addClass('btn-danger').find('i').removeClass('fa-phone fa-remove').addClass('fa-close');
                    break;
                case 'disabled':
                    $('#phone_num').attr('disabled', 'disabled').val('AIScript-225');
                    $('#phone_call_btn').attr('disabled', 'disabled').removeClass('btn-default btn-success btn-danger').addClass('btn-default').find('i').removeClass('fa-phone fa-remove').addClass('fa-phone');
                    break;
            }
        },
        lastCallRecord: null,
        appendCallRecord: function() {
            if (this.lastCallRecord == null) {
                return;
            }
            this.lastCallRecord['type'] = [ this.lastCallRecord['direction'], this.lastCallRecord['flag'] ];
            this.lastCallRecord['now_time'] = Date.now();
            var record = {
                row: this.lastCallRecord
            };
            //console.log(record);
            this.lastCallRecord = null;
            $.post('/admin/call/record/add', record, function(result) {
                if (window.top.refreshCallRecord) {
                    window.top.refreshCallRecord();
                }
                //alert('ok!');
            });
        },
        init: function(SIP, cfg) {
            $('<video id="remoteAudio" class="hide"></video>').appendTo($('body'));
            $('<audio id="audio_ringin" src="/assets/sound/ringin.mp3" loop="loop" preload="load" class="hide"></audio>').appendTo($('body'));
            $('<audio id="audio_ringback" src="/assets/sound/ringback.mp3" loop="loop" preload="load" class="hide"></audio>').appendTo($('body'));
            $('<audio id="audio_hangup" src="/assets/sound/hangup.mp3" preload="load" class="hide"></audio>').appendTo($('body'));
            // Create a Simple interface with a user named bob and a remote video element in the DOM
            this.ua = {
                    'uri': cfg.extension + '@'  + cfg.sip_domain,
                    'wsServers': [ cfg.ws_server ],
                    'authorizationUser': cfg.extension,
                    'password': cfg.extension_password,
                    'registerExpires': cfg.sip_register_expires,
                    'traceSip': cfg.sip_trace,
                    'rel100':  SIP.C.supported.UNSUPPORTED
                };
            //console.log(this.ua);
            this.simple = new SIP.WebRTC.Simple({
                    media: {
                    remote: {
                        //video: document.getElementById('remoteVideo'),
                        // This is necessary to do an audio/video call as opposed to just a video call
                        audio: document.getElementById('remoteAudio')
                    }
                },
                ua: this.ua,
            });
            var that = this;
            this.simple.on('registered', function() {
                $('#sip_state').html('<i class="fa fa-circle text-success"></i> 已注册');
                $('#phone_status').html('');
                that.set_phone_state('idle');
                //alert('registered');
            });
            this.simple.on('unregistered', function() {
                $('#sip_state').html('<i class="fa fa-circle text-danger"></i> 未注册');
                $('#phone_status').html('');
                that.set_phone_state('disabled');
            });
            this.simple.on('ended', function() {
                if (that.lastCallRecord) {
                    //console.log('ended:' + Date.now());
                    that.lastCallRecord['end_stamp'] = Date.now();
                }
                that.appendCallRecord();
                that.set_phone_state('idle');
                document.getElementById('audio_hangup').play();
                $('.btn-phone').css({'pointer-events':'auto'}).find('i').removeClass('fa-volume-control-phone').addClass('fa-phone');
            });
            this.simple.on('new', function() {
                //$('#phone_status').html(''); 
            });
            this.simple.on('ringing', function(session) {
                var gateway = '';
                var auto_answer = false;
                if (session.request.headers['X-Gateway'] && session.request.headers['X-Gateway'][0] && session.request.headers['X-Gateway'][0]['raw']) {
                    gateway = session.request.headers['X-Gateway'][0]['raw'];
                }
                if (session.request.headers['Call-Info'] && session.request.headers['Call-Info'][0] && session.request.headers['Call-Info'][0]['raw']) {
                    var call_info = session.request.headers['Call-Info'][0]['raw'];
                    if (/answer-after=\d+/.test(call_info)) {
                        auto_answer = true;
                    }
                }
                var displayName = session.remoteIdentity.displayName;
                var user = session.remoteIdentity.uri.user;
                that.lastCallRecord = {
                    direction: 'callin',
                    flag: 'missed',
                    caller_name: displayName,
                    caller_number: user,
                    callee_number: extension_cfg.extension,
                    gateway: gateway,
                    start_stamp: Date.now(),
                    answer_stamp: null,
                    end_stamp: null
                };
                that.set_phone_state('ringing');
                $('#phone_num').val(user);
                $('#phone_status').html('振铃中...');
                that.incomingLayerIndex = Layer.confirm('<h2 class="text-center">' + displayName + '</h2>对方号码：' + user + '<br/>　　线路：<span class="label label-primary">' + gateway + '</span><br/>　　被叫：' + cfg.extension, {closeBtn: 1, title: __('新来电') /*+ ' - ' + '051250666636'*/, btn: ['接 听','拒 绝'], cancel: function() { SIPClient.reject(); that.incomingLayerIndex = null; }}, function(){ SIPClient.answer(); Layer.close(that.incomingLayerIndex); that.incomingLayerIndex = null; }, function(){ SIPClient.reject(); that.incomingLayerIndex = null; });
                //alert('ringing');
                //that.simple.answer();
                if (auto_answer) {
                    if (that.lastSetTimeout) {
                        clearTimeout(that.lastSetTimeout);
                    }
                    that.lastSetTimeout = setTimeout(function() {
                        if (that.incomingLayerIndex != null) {
                            Layer.close(that.incomingLayerIndex);
                            that.incomingLayerIndex = null;
                            SIPClient.answer();
                            return;
                        }
                    }, 3000);
                }
            });
            this.simple.on('connecting', function() {
                $('#phone_status').html('呼叫中...');
                document.getElementById('audio_ringback').play();
            });
            this.simple.on('message', function(message) {
                //console.log(message);
                if (message.contentType == 'text/info-gateway') {
                    if (that.lastCallRecord) {
                        that.lastCallRecord['gateway'] = message.body;
                    }
                }
                if (message.contentType == 'text/info-asr') {
                    Toastr.success('ASR: ' + message.body);
                } else if (message.contentType == 'text/info-tts') {
                    Toastr.info('TTS: ' + message.body);
                }
            });
            this.simple.on('connected', function(session) {
                //console.log(session);
                //alert('t');
                //console.log('answer:' + Date.now());
                if (that.lastCallRecord != null) {
                    that.lastCallRecord['flag'] = 'answered';
                    that.lastCallRecord['answer_stamp'] = Date.now();
                }
                that.set_phone_state('calling');
                that.startTime = session.startTime;
                $('#phone_status').html('<i class="fa fa-microphone"></i> <span>00:01</span>');
                that.durationCounterInterval = setInterval(function() {
                    if (that.startTime == null) {
                        clearInterval(that.durationCounterInterval);
                        return;
                    }
                    var nowTime =  Date.now();
                    var duration = Math.ceil((nowTime - that.startTime) / 1000);
                    var duration_min = parseInt(duration / 60);
                    var duration_sec = parseInt(duration  - duration_min * 60)
                    $('#phone_status').find('span').html((duration_min < 10 ? '0' : '') + duration_min.toString() + ':' + (duration_sec < 10 ? '0' : '') + duration_sec.toString());
                }, 1000);
            });
            this.simple.on('mute', function() {
                $('#phone_status i').removeClass('fa-microphone').addClass('fa-microphone-slash');
            });
            this.simple.on('unmute', function() {
                $('#phone_status i').removeClass('fa-microphone-slash').addClass('fa-microphone');
            });
            $('#phone_call_btn').click(function(e) {
                e.stopPropagation();
                e.preventDefault();
                if ($('#phone_num').val() == '') {
                    return;
                }
                if (that.state == 'idle') {
                    SIPClient.call($('#phone_num').val());
                } else if (that.state == 'ringing') {
                    SIPClient.reject();
                } else {
                    SIPClient.hangup();
                }
            });
            $('#phone_num').bind('keypress', function(e) {
                if (e.keyCode == 13) {
                    e.stopPropagation();
                    e.preventDefault();
                    $('#phone_call_btn').click();
                }
            });
            
            $(document).on("click", '.btn-phone',function(e) {
                var phoneId=$(this).parent().parent().find('td').eq(1).text();
                // if ($(this).find('i').hasClass('fa-volume-control-phone')) {
                //     SIPClient.hangup();
                //     $('.btn-phone').find('i').removeClass('fa-volume-control-phone').addClass('fa-phone');
                // }
                if (that.state == 'idle') {
                    SIPClient.call('AIScript-'+phoneId+'')
                    $(this).find('i').removeClass('fa-phone').addClass('fa-volume-control-phone');
                    // $('.btn-phone').css({'pointer-events':'none'});
                    $(this).parent().parent().siblings().find('.btn-phone').css({'pointer-events':'none'});
                } else if (that.state == 'ringing') {
                    SIPClient.reject();
                    $(this).find('i').removeClass('fa-phone').addClass('fa-volume-control-phone');
                    // $('.btn-phone').css({'pointer-events':'none'});
                    $(this).parent().parent().siblings().find('.btn-phone').css({'pointer-events':'none'});
                } else {
                    SIPClient.hangup();
                    $('.btn-phone').css({'pointer-events':'auto'}).find('i').removeClass('fa-volume-control-phone').addClass('fa-phone');
                }
            });
            // $(document).on("click", "#btn-reset ,.layui-layer-close1", function () {
            //     console.log("挂断成功！")
            //     SIPClient.hangup();
            //     $('.btn-phone').css({'pointer-events':'auto'}).find('i').removeClass('fa-volume-control-phone').addClass('fa-phone');
            //      Layer.closeAll();
            // });
        },
        call: function(num) {
            var pattern = /^\*{0,1}\d+$/i;
            if (!pattern.test(num)) {
                //Backend.api.toastr.error(__('电话号码只能为数字 !<br/>拨打分机请在分机号前加拨 * 号'));
                //return false;
            }
            this.lastCallRecord = {
                direction: 'callout',
                flag: 'missed',
                caller_name: extension_cfg.extension,
                caller_number: extension_cfg.extension,
                callee_number: num,
                //gateway: gateway,
                start_stamp: Date.now(),
                answer_stamp: null,
                end_stamp: null,
             };
            this.set_phone_state('calling');
            $('#phone_status').html('呼叫中...');
            this.simple.call(num);
        },
        hangup: function() {
            this.simple.hangup();
            //this.set_phone_state('idle');
        },
        reject: function() {
            if (this.state == 'ringing') {
                this.simple.reject();
            }
        },
        answer: function() {
            if (this.state == 'ringing') {
                //console.log('ringing:' + Date.now());
                document.getElementById('audio_ringin').pause();
                $('#phone_status').html('接通中...');
                this.simple.answer();
            }
        },
        mute: function() {
            if (this.state != 'calling') {
                return;
            }
            var mute_i = $('#phone_status i');
            if (mute_i.hasClass('fa-microphone')) {
                this.simple.hold();
            } else {
                this.simple.unhold();
            }
        }
    }
    return SIPClient;
})
